package com.demo.util;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author：不想早起
 * @Package：com.demo.util
 * @Project：ESDemo
 * @name：ESUtils
 * @Date：2024/2/26 20:55
 * @Filename：ESUtils
 *
 */
@Component
public class ESUtils {
    // 索引
    @Autowired
    private RestHighLevelClient client;

    public Boolean existIndex(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        /*exists判断当前索引是否存在*/
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);//是否存在
        return exists;
    }
    public void createIndex(String indexName) throws IOException {
        Boolean existIndex = existIndex(indexName);
        if (!existIndex){
            //1、创建索引请求
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            //2、客户端，执行请求IndicesClient  CreateIndexResponse获得对应的响应
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(createIndexResponse);
        }
    }
    public void deleteIndex(String indexName) throws IOException {
        Boolean existIndex = existIndex(indexName);
        if (existIndex){
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
            /*删除*/
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            System.out.println(delete.isAcknowledged());
        }
    }


    //3、获取数据并实现搜索实现高亮功能
    public List<Map<String,Object>> searchPageHighLightBuilder(String keyword,int pageNo,int pageSize) throws IOException {
        if (pageNo <= 1){
            pageNo = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//是否开启多个高亮
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        for (SearchHit hit : searchResponse.getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//这是原来的结果
            //解析高亮的字段,将原来的字段换为高亮的字段即可
            if(title != null){
                Text[] fragments = title.fragments();//获得到对应的高亮字段
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title",n_title);//高亮的字段替换调原来的内容即可 替换高亮的字段
            }
            mapList.add(sourceAsMap);
        }
        return mapList;
    }


}
